package pers.gxm.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/myController")
public class MyController {
    /**
     * 最先的请求，跳转到前端页面
     * @return
     */
    @GetMapping("/login")
    public String login(){
        System.out.println("开始调用login方法");
        return "login";
    }

    @GetMapping("/rememberMe")
    public String testRememberMe(HttpSession session){
            session.setAttribute("user","测试rememberMe");
            return "main";
    }

    @GetMapping("userLoginRoles")
    @ResponseBody
    @RequiresRoles("admin")
    public String userLoginRoles(){
        System.out.println("登录验证角色功能是否生效");
        return "验证角色成功！";
    }

    @GetMapping("/userLoginPermissions")
    @ResponseBody
    @RequiresPermissions("user:delete")
    public String userLoginPermissions(){
        System.out.println("登录验证权限功能是否生效");
        return "验证权限成功！";
    }

    @PostMapping("/userLogin")
    public String userLogin(@RequestParam("name") String username, @RequestParam("pwd") String pwd, @RequestParam(required = false) boolean rememberMe, HttpSession session){
//     TODO   1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
//     TODO   2.获取前端传来的账号密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,pwd,rememberMe);
        try {
            subject.login(usernamePasswordToken);
            session.setAttribute("user",usernamePasswordToken.getPrincipal().toString());
            return "main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
//            return "登录失败";
//            throw new RuntimeException("登录失败");
            throw e;
        }


    }
}
